<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ContextKey;
use App\Constants\ErrorCode;
use App\Dao\CooperativeDao;
use App\Exception\BusinessException;

use App\Model\Cooperative;
use App\Utils\Log;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Constants\Model\Cooperative as CooperativeConstants;

class ClientMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;


    /**
     * @Inject()
     * @var CooperativeDao
     */
    private $cooperativeDao;


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $domain = $request->getHeaderLine('Domain');

        Log::get()->info('-------------------------domain:'.$domain);
        /** @var Cooperative $cooperative */
        $cooperative = $this->cooperativeDao->first(['domain' => $domain]);

        if (!$cooperative) {
            throw new BusinessException(ErrorCode::DOMAIN_ERROR);
        }

        //合作商被封
        if ($cooperative->status != CooperativeConstants::STATUS_UNBLOCK) {
            throw new BusinessException(ErrorCode::COOPERATIVE_DISABLE);
        }

        Context::set(ContextKey::COOPERATIVE, $cooperative);
        return $handler->handle($request);
    }

}